package com.socialsoftware.adapter;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.socialsoftware.R;
import com.socialsoftware.model.Contact;
import com.socialsoftware.ui.Contact.SidebarIndexView;
import com.socialsoftware.util.AvatarUtil;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ContactAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements SidebarIndexView.OnLetterSelectedListener {
    private static final int VIEW_TYPE_HEADER = 1;
    private static final int VIEW_TYPE_NORMAL = 0;
    private static final int VIEW_TYPE_SPECIAL = 2;
    
    private List<Contact> contacts;
    private Context context;
    private OnContactClickListener listener;
    private Map<String, Integer> letterPositionMap = new HashMap<>();
    
    public ContactAdapter(Context context, List<Contact> contacts) {
        this.context = context;
        this.contacts = contacts;
        updateLetterPositionMap();
    }
    
    public void setContacts(List<Contact> contacts) {
        this.contacts = contacts;
        updateLetterPositionMap();
        notifyDataSetChanged();
    }
    
    private void updateLetterPositionMap() {
        letterPositionMap.clear();
        for (int i = 0; i < contacts.size(); i++) {
            Contact contact = contacts.get(i);
            if (contact.getType() == Contact.TYPE_HEADER) {
                String letter = contact.getName();
                if (!letterPositionMap.containsKey(letter)) {
                    letterPositionMap.put(letter, i);
                }
            }
        }
    }
    
    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        
        switch (viewType) {
            case VIEW_TYPE_HEADER:
                View headerView = inflater.inflate(R.layout.item_contact_header, parent, false);
                return new HeaderViewHolder(headerView);
            case VIEW_TYPE_SPECIAL:
                View specialView = inflater.inflate(R.layout.item_contact_special, parent, false);
                return new SpecialViewHolder(specialView);
            default:
                View normalView = inflater.inflate(R.layout.item_contact, parent, false);
                return new NormalViewHolder(normalView);
        }
    }
    
    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        Contact contact = contacts.get(position);
        
        switch (holder.getItemViewType()) {
            case VIEW_TYPE_HEADER:
                HeaderViewHolder headerHolder = (HeaderViewHolder) holder;
                headerHolder.tvHeader.setText(contact.getName());
                break;
            case VIEW_TYPE_SPECIAL:
                SpecialViewHolder specialHolder = (SpecialViewHolder) holder;
                specialHolder.tvName.setText(contact.getName());
                
                // 设置特殊联系人图标
                setSpecialIcon(specialHolder.ivSpecialIcon, contact.getSpecialIcon());
                
                final int specialPos = position;
                specialHolder.itemView.setOnClickListener(v -> {
                    if (listener != null) {
                        listener.onContactClick(contacts.get(specialPos));
                    }
                });
                break;
            default:
                NormalViewHolder normalHolder = (NormalViewHolder) holder;
                // 优先使用备注名(remark)，如果备注名为空则使用名称(name)
                String displayName = contact.getRemark();
                if (displayName == null || displayName.isEmpty()) {
                    displayName = contact.getName();
                }
                normalHolder.tvName.setText(displayName);
                
                // 设置联系人头像
                setContactAvatar(normalHolder.ivAvatar, contact);
                
                // Hide divider for last item in a section
                boolean hideDivider = (position == contacts.size() - 1) || 
                        (position + 1 < contacts.size() && contacts.get(position + 1).getType() == Contact.TYPE_HEADER);
                normalHolder.divider.setVisibility(hideDivider ? View.INVISIBLE : View.VISIBLE);
                
                final int normalPos = position;
                normalHolder.itemView.setOnClickListener(v -> {
                    if (listener != null) {
                        listener.onContactClick(contacts.get(normalPos));
                    }
                });
                break;
        }
    }
    
    @Override
    public int getItemCount() {
        return contacts != null ? contacts.size() : 0;
    }
    
    @Override
    public int getItemViewType(int position) {
        return contacts.get(position).getType();
    }
    
    public void setOnContactClickListener(OnContactClickListener listener) {
        this.listener = listener;
    }
    
    @Override
    public void onLetterSelected(String letter) {
        // Called from SidebarIndexView when a letter is selected
        Integer position = letterPositionMap.get(letter);
        if (position != null && listener != null) {
            listener.onLetterSelected(letter, position);
        }
    }
    
    @Override
    public int getPositionForLetter(String letter) {
        Integer position = letterPositionMap.get(letter);
        return position != null ? position : -1;
    }
    
    // ViewHolders
    static class NormalViewHolder extends RecyclerView.ViewHolder {
        ImageView ivAvatar;
        TextView tvName;
        View divider;
        
        NormalViewHolder(@NonNull View itemView) {
            super(itemView);
            ivAvatar = itemView.findViewById(R.id.iv_avatar);
            tvName = itemView.findViewById(R.id.tv_name);
            divider = itemView.findViewById(R.id.divider);
        }
    }
    
    static class HeaderViewHolder extends RecyclerView.ViewHolder {
        TextView tvHeader;
        
        HeaderViewHolder(@NonNull View itemView) {
            super(itemView);
            tvHeader = itemView.findViewById(R.id.tv_header);
        }
    }
    
    static class SpecialViewHolder extends RecyclerView.ViewHolder {
        ImageView ivSpecialIcon;
        TextView tvName;
        View divider;
        
        SpecialViewHolder(@NonNull View itemView) {
            super(itemView);
            ivSpecialIcon = itemView.findViewById(R.id.iv_special_icon);
            tvName = itemView.findViewById(R.id.tv_special_name);
            divider = itemView.findViewById(R.id.divider);
        }
    }
    
    public interface OnContactClickListener {
        void onContactClick(Contact contact);
        void onLetterSelected(String letter, int position);
    }
    
    /**
     * 设置联系人头像
     * @param imageView 头像ImageView
     * @param contact 联系人对象
     */
    private void setContactAvatar(ImageView imageView, Contact contact) {
        // 优先使用备注名(remark)，如果备注名为空则使用名称(name)
        String displayName = contact.getRemark();
        if (displayName == null || displayName.isEmpty()) {
            displayName = contact.getName();
        }
        
        String avatar = contact.getAvatar();
        
        // 检查是否有真实头像
        if (avatar != null && !avatar.isEmpty()) {
            // 在实际应用中，这里应该使用图片加载库如Glide或Picasso加载网络或本地图片
            // 例如：Glide.with(context).load(avatar).circleCrop().into(imageView);
            
            // 由于这是示例，我们使用名字首字母的头像代替
            imageView.setImageDrawable(AvatarUtil.getNameAvatar(context, displayName));
        } else {
            // 没有头像时使用名字首字母的头像
            imageView.setImageDrawable(AvatarUtil.getNameAvatar(context, displayName));
        }
        
        // 移除背景，因为我们的头像已经包含背景
        imageView.setBackground(null);
    }
    
    /**
     * 设置特殊联系人图标
     * @param imageView 图标ImageView
     * @param iconType 图标类型
     */
    private void setSpecialIcon(ImageView imageView, String iconType) {
        // 根据特殊联系人类型设置不同的图标
        int iconResId;
        int backgroundColor = 0xFF07C160; // 微信绿色
        
        if (iconType == null) {
            iconResId = android.R.drawable.ic_menu_myplaces; // 默认图标
        } else {
            switch (iconType) {
                case "new_friends_icon":
                    iconResId = android.R.drawable.ic_menu_add;
                    break;
                case "group_chat_icon":
                    iconResId = android.R.drawable.ic_menu_myplaces;
                    break;
                case "tags_icon":
                    iconResId = android.R.drawable.ic_menu_edit;
                    break;
                case "official_accounts_icon":
                    iconResId = android.R.drawable.ic_menu_compass;
                    break;
                default:
                    iconResId = android.R.drawable.ic_menu_myplaces;
                    break;
            }
        }
        
        // 创建圆形背景的图标
        Bitmap bitmap = Bitmap.createBitmap(120, 120, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        
        // 绘制圆形背景
        Paint backgroundPaint = new Paint();
        backgroundPaint.setColor(backgroundColor);
        backgroundPaint.setAntiAlias(true);
        canvas.drawCircle(60, 60, 60, backgroundPaint);
        
        // 设置图标
        imageView.setBackground(null);
        imageView.setImageDrawable(new BitmapDrawable(context.getResources(), bitmap));
        
        // 在实际应用中，您应该在圆形背景上绘制适当的图标
        // 这里简单设置一个系统图标
        imageView.setImageResource(iconResId);
        imageView.setScaleType(ImageView.ScaleType.CENTER);
    }
} 